import GetLocation from '@/components/GetLocation/';
import { regeo } from '@/dataTransfer/address';
import pLocation from '@/images/common/location.png';
import { Image, Text, View } from '@tarojs/components';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import AddressSelect from '../../addressSelect/index';
import styles from './index.module.scss';

const isValidLocation = (location) => {
  return location?.addressId || location?.adCode;
};

const CartAddress = ({ dispatch, selectedAddress,defaultAddress, onChange,onShowModal }) => {
  const [isShowAddressSelect, setIsShowAddressSelect] = useState(false);
  const [curLocation, setCurLocation] = useState();
  let addressVal = defaultAddress
  const getLocationAddr = (location) => {
    regeo(location)
      .then(({ address, adcode }) => {
        dispatch({
          type: 'productCar/setLocationAddress',
          payload: { ...location, address: address },
        });

        setCurLocation({ ...location, adCode: adcode, fullAddress: address });
      })
      .catch(console.warn);
  };

  const updateCurLocation = (location) => {
    if (!location) {
      return;
    }

    // 服务器的地址
    if (location.addressId) {
      setCurLocation(location);
      return;
    }

    // 由经纬度, 转换 adCode
    if (!location.adCode && location.latitude) {
      getLocationAddr(location);
    }
  };
  useEffect(()=>{
    dispatch({ type: 'giftCard/allAddressesModel' });
  },[])
  useEffect(() => {
    // 当前已经存在地址了
    if (isValidLocation(curLocation)) {
      return;
    }
    // 已经选择, 从已选择的获取详细
    if (addressVal?.id) {
      const { latitude, longitude, address, houseNumber } = addressVal;

      updateCurLocation({
        latitude,
        longitude,
        addressId: addressVal.id,
        fullAddress: address + houseNumber,
      });

      return;
    }
    // 否则的话会走 <GetLocation >, 然后调用 updateCurLocation
  }, [addressVal, curLocation]);

  // 回传 地址信息
  useEffect(() => {
    if (curLocation) {
      onChange(curLocation);
    }
  }, [curLocation]);

  return (
    <View className={styles.CartAddress}>
      {addressVal?.id === undefined && <GetLocation handleLocation={updateCurLocation} />}

      <AddressSelect
        isOpened={isShowAddressSelect}
        handleClose={(sa) => {
          setIsShowAddressSelect(false);
          onShowModal(false)
          // 回传了选择的地址, 则进行更新
          if (sa) {
            const { id, latitude, longitude, address, houseNumber } = sa;

            updateCurLocation({
              latitude,
              longitude,
              addressId: id,
              fullAddress: address + houseNumber,
            });
          }
        }}
      />

      <View
        className="location"
        onClick={() => {
          setIsShowAddressSelect(true);
          onShowModal(true)
        }}
      >
        <Image className="icon" src={pLocation} />
        <Text className="txt omit">
          {curLocation?.fullAddress ? '配送至：' + curLocation.fullAddress : '请选择收货地址'}
        </Text>
      </View>
    </View>
  );
};

export default connect(({ loading, productCar }) => ({
  selectedAddress: productCar.selectedAddress,
  defaultAddress: productCar.defaultAddress,
  loading,
}))(CartAddress);
